package com.aac.framwork.aacframwork.repository;

import android.arch.lifecycle.LiveData;

import com.aac.framwork.aacframwork.repository.datas.cache.UserCache;
import com.aac.framwork.aacframwork.entity.User;
import com.aac.framwork.aacframwork.repository.dao.UserDao;
import com.aac.framwork.aacframwork.webservice.WebService;

import java.io.IOException;
import java.util.concurrent.Executor;

import javax.inject.Inject;
import javax.inject.Singleton;

import retrofit2.Response;

@Singleton
public class UserRepository {

    //这不是最好的实现方式
    private final WebService webService;
    private final UserDao userDao;
    private final Executor executor;

    private UserCache userCache;

    @Inject
    public UserRepository(WebService webService, UserDao userDao, Executor executor) {
        this.webService = webService;
        this.userDao = userDao;
        this.executor = executor;
    }

    public LiveData<User> getUser(Long userId) {


        /*final MutableLiveData<User> data = new MutableLiveData<>();
        webService.getUser(userId).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {

                data.setValue(response.body());
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });*/

        //最总数据库为应用的最终数据提供着
        refreshUser(userId);
        return userDao.load(userId);
    }


    private void refreshUser(final Long userId) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                boolean userExists = userDao.hasUser(userId);
                if (!userExists) {
                    try {
                        Response response = webService.getUser(userId).execute();
                        userDao.save((User) response.body());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        };


        executor.execute(runnable);
    }
}
